package leetcode._082;
/**
 * title: 82. Remove Duplicates from Sorted List II
 * Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
 *
 * Example 1:
 *
 * Input: 0->1->2->3->3->4->4->5
 * Output: 1->2->5
 * Example 2:
 *
 * Input: 1->1->1->2->3
 * Output: 2->3
 */
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */

/**
 * <a>https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/</>
 *
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        this.head = null;
        if(head == null) {
            return null;
        }
        ListNode temp = head;
        int prev = temp.val - 1;
        try {
            while (temp.next != null) {
                while (temp.val
                        == temp.next.val) {
                    temp = temp.next;
                    prev = temp.val;
                    continue;
                }
                if (prev != temp.val) {
                    prev = temp.val;
                    addNode(temp.val);
                }
                temp = temp.next;
            }
            addNode(temp.val);
        } catch (Exception e) {

        }
        return this.head;
    }
    ListNode head = null;
    public void addNode(int data){
        ListNode newNode = new ListNode(data);
        if(head == null){
            head = newNode;
            return;
        }
        ListNode temp = head;
        while(temp.next != null){
            temp = temp.next;
        }
        temp.next = newNode;
    }
}